package summary;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;


/**
 * @Author: 海琳琦
 * @Date: 2022/3/16 10:31
 * https://leetcode-cn.com/problems/combination-sum/
 */
public class Title40 {

    List<List<Integer>> result = new ArrayList<>();
    LinkedList<Integer> list = new LinkedList<>();

    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        backTracking(candidates, target, 0);
        return result;
    }

    private void backTracking(int[] candidates, int target, int start) {
        if (target == 0) {
            result.add(new ArrayList<>(list));
            return;
        }
        boolean[] flag = new boolean[51];
        for (int i = start; i < candidates.length; i++) {
            if (target - candidates[i] < 0) {
                break;
            }
            if (flag[candidates[i]]) {
                continue;
            }
            list.add(candidates[i]);
            flag[candidates[i]] = true;
            backTracking(candidates, target - candidates[i], start + 1);
            list.removeLast();
        }
    }



    public static List<List<Integer>> combinationSum3(int[] candidates, int target) {
        List<List<Integer>> result = new ArrayList<>();
        LinkedList<Integer> temp = new LinkedList<>();
        Arrays.sort(candidates);
        backTracking1(result, temp, candidates, target, 0);
        return result;
    }

    private static void backTracking1(List<List<Integer>> result, LinkedList<Integer> temp, int[] candidates, int target, int start) {
        if (target == 0) {
            result.add(new ArrayList<>(temp));
            return;
        }
        //层次去重
        boolean[] flag = new boolean[50];
        for (int i = start; i < candidates.length; i++) {
            if (target - candidates[i] < 0) {
                continue;
            }
            if (flag[candidates[i] - 1]) {
                continue;
            }
            temp.add(candidates[i]);
            flag[candidates[i] - 1] = true;
            backTracking1(result, temp, candidates, target - candidates[i], i + 1);
            temp.removeLast();
        }
    }


    public static void main(String[] args) {
        int[] candidates = {10,1,2,7,6,1,5};
        int target = 8;
        combinationSum3(candidates, target);
    }
}
